package cn.com.java.service.impl;

import cn.com.java.mapper.ProductMapper;
import cn.com.java.mapper.SysUserMapper;
import cn.com.java.model.Product;
import cn.com.java.model.ProductImages;
import cn.com.java.model.SysUser;
import cn.com.java.service.ProductImagesService;
import cn.com.java.service.ProductService;
import cn.com.java.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liushuntao
 * @date 2024/3/19
 */
@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    private final ProductImagesService productImagesService;


    @Override
    public boolean save(Product product) {
        super.save(product);
        product.getImages().forEach(p -> {
            p.setId(null);
            p.setProductId(product.getId());
        });
        productImagesService.saveBatch(product.getImages());
        return Boolean.TRUE;
    }

    @Override
    public Map<Long, List<ProductImages>> getByimagesByIds(List<Long> ids) {
        List<ProductImages> productImagesList = productImagesService.getByIds(ids);
        return productImagesList.stream().collect(Collectors.groupingBy(ProductImages::getProductId));
    }

    @Override
    public String release(Long id) {
        UpdateWrapper<Product> productUpdateWrapper = new UpdateWrapper<>();
        productUpdateWrapper.eq("id", id).set("status", 1);
        update(productUpdateWrapper);
        return "发布成功";
    }

    @Override
    public boolean updateById(Product product) {
        QueryWrapper<ProductImages> productImagesWrapper = new QueryWrapper<>();
        productImagesWrapper.eq("product_id", product.getId());
        productImagesService.remove(productImagesWrapper);
        if (!product.getImages().isEmpty()) {
            product.getImages().forEach(p -> {
                p.setId(null);
                p.setProductId(product.getId());
            });
            productImagesService.saveBatch(product.getImages());
        }
        return super.updateById(product);
    }

    @Override
    public Product getById(Serializable id) {
        Product byId = super.getById(id);
        List<Long> ids = new ArrayList<>();
        ids.add(Long.valueOf(id.toString()));
        List<ProductImages> productImages = productImagesService.getByIds(ids);
        byId.setImages(productImages);
        return byId;
    }
}
